<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/25 0025
 * Time: 20:00
 */

namespace Api\Service;


class FileService
{
    public function save($name, $content)
    {
        try {
            $file = $this->path($name);
            file_exists(dirname($file)) || mkdir(dirname($file), 0755, true);
            if (file_put_contents($file, $content)) return $this->info($name);
        } catch (\Exception $e) {
            //todo::记录文件存储异常
            $error_path = 'error/file/'.date('y_m_d').'log';
            file_exists(dirname($error_path)) || mkdir(dirname($error_path), 0755, true);
            file_put_contents($error_path,__METHOD__ . " 本地文件存储失败，{$e->getMessage()}".PHP_EOL,FILE_APPEND);
        }
        return null;
    }
    /**
     * 获取服务器URL前缀
     * @param string $name 文件名称
     * @return string|null
     */
    public function base($name = '')
    {
        $root = rtrim(dirname('test'), '\\/');
        return "{$root}/upload/{$name}";
    }
    /**
     * 获取文件信息
     * @param string $name 文件名称
     * @return array|null
     */
    public function info($name)
    {
        if ($this->has($name) && is_string($file = $this->path($name))) {
            return ['file' => $file, 'hash' => md5_file($file), 'url' => $this->base($name), 'key' => "upload/{$name}"];
        }
        return null;
    }
    /**
     * 获取文件路径
     * @param string $name 文件名称
     * @return string
     */
    public function path($name)
    {
        $path = 'Public/upload';
        return str_replace('\\', '/', __ROOT__ . "/{$path}/{$name}");
    }
    /**
     * 检查文件是否已经存在
     * @param string $name 文件名称
     * @return boolean
     */
    public function has($name)
    {
        return file_exists($this->path($name));
    }
}